package cn.aoyu.test.service.user.impl;

import cn.aoyu.test.bean.user.User;
import cn.aoyu.test.mapper.user.UserMapper;
import cn.aoyu.test.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName: UserServiceImpl
 * @Auther: xww
 * @Date: 2019/5/16 0016 14:27
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	public void addUser(User user) {
		userMapper.insertUser(user);
	}

	@Override
	public void updateUser(User user) {
		userMapper.updateUser(user);
	}

	@Override
	public User getUser(Integer id) {
		return userMapper.getUser(id);
	}

	@Override
	@Transactional
	public User transactionalMethod(User user) {
		userMapper.insertUser(user);
		// 此处换成Exception就不会回滚了
		throw new RuntimeException("抛出错误数据库应该回滚");
//		return userMapper.getUser(1);
	}

	@Override
	@Transactional
	public void dbInnoDBLock() {
		// 但是必须在一个事务中,才能有效果 要用	@Transactional 注解才行
		// 如果没有加索引的话，就会是表锁
		// 如果给id字段加了索引，就会是行锁
		User user = getUser(12);
		user.setAge(user.getAge() + 1);
		updateUser(user);
		System.out.println(user.toString());
	}

}
